<template>
    <div>
        <div class="login-container">
            <!-- 登录表单 -->
            <div class="login-body">
                <el-tooltip class="item" effect="dark" content="回到首页" placement="top">
                    <button class="back-btn" @click="backToHome">
                        <el-icon size="22" color="#666666">
                            <Back />
                        </el-icon>
                    </button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="currentForm === 'login' ? '账号密码登录' : '扫码登录'"
                    placement="top">
                    <button class="switch-form-btn" @click="handleSwitchForm">
                        <el-icon size="22" color="#666666" v-if="currentForm === 'login'">
                            <User />
                        </el-icon>
                        <i class="fas fa-qrcode" v-else></i>
                    </button>
                </el-tooltip>
                <!-- 微信扫码登录 -->
                <div v-show="currentForm === 'login'" class="form-container">
                    <div class="qrcode-content">
                        <div class="qrcode-box">
                            <!-- 这里放二维码图片 -->
                            <img v-lazy="'https://img.shiyit.com/qrcode.jpg'" :key="'https://img.shiyit.com/qrcode.jpg'"
                                alt="微信二维码" />
                        </div>
                        <p class="qrcode-tip">
                            登录验证码：
                            <span class="code-text">{{ wechatForm.code }}</span>
                            <span class="code-text" v-if="wechatForm.code === '验证码已失效'">
                                <i class="fas fa-sync-alt" @click="getWechatLoginCode"></i>
                            </span>
                        </p>
                        <p class="qrcode-tip">微信扫码关注公众号，并发送验证码</p>
                    </div>

                    <div class="divider">
                        <el-divider>其他登录方式</el-divider>
                    </div>

                    <div class="third-party-login">
                        <div v-for="(item, type) in loginTypes" :key="type" class="login-icon-wrapper"
                            @click="handleThirdPartyLogin(type)" v-if="type !== 'wechat'">
                            <el-tooltip :content="item.title" placement="top">
                                <div :class="['login-icon', type]">
                                    <i :class="item.icon"></i>
                                </div>
                            </el-tooltip>
                        </div>
                    </div>
                </div>

                <!-- 账号密码登录表单 -->
                <div v-show="currentForm === 'account'" class="form-container">
                    <div class="form-header">
                        <h2 class="form-title">账号密码登录</h2>
                        <p class="form-subtitle">欢迎回来,请输入您的账号</p>
                    </div>

                    <el-form :model="loginForm" :rules="rules" ref="ruleFormRef">
                        <el-form-item class="form-item" prop="username">
                            <el-input :prefix-icon="User" v-model="loginForm.username" placeholder="请输入用户名"
                                @keyup.enter.native="handleLogin" size="large"/>
                        </el-form-item>

                        <el-form-item class="form-item" prop="password">
                            <el-input :prefix-icon="Lock" v-model="loginForm.password" placeholder="请输入密码"
                                @keyup.enter.native="handleLogin" show-password size="large" />
                        </el-form-item>

                        <div class="form-options">
                            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                        </div>

                        <el-form-item class="form-item">
                            <el-button class="submit-btn ripple" :loading="loading" @click="handleLogin" type="primary">
                                登 录
                            </el-button>
                        </el-form-item>
                    </el-form>

                    <div class="form-switch">
                        <a @click="switchForm('register')">立即注册</a>
                        <span class="divider-line">|</span>
                        <a @click="switchForm('forgot')">忘记密码?</a>
                    </div>
                </div>

                <!-- 注册表单 -->
                <div v-show="currentForm === 'register'" class="form-container">
                    <div class="form-header">
                        <h2 class="form-title">注册账号</h2>
                        <p class="form-subtitle">欢迎注册,请输入您的账号</p>
                    </div>
                    <el-form :model="registerForm" :rules="rules" ref="registerFormRef">
                        <el-form-item lable="昵称" prop="nickname">
                            <el-input :prefix-icon="User" v-model="registerForm.nickname"
                                placeholder="请输入昵称" />
                        </el-form-item>

                        <el-form-item class="form-item" prop="email">
                            <el-input :prefix-icon="Message" v-model="registerForm.email" placeholder="请输入邮箱" />
                        </el-form-item>

                        <el-form-item class="form-item" prop="code">
                            <el-input :prefix-icon="Key" v-model="registerForm.code" placeholder="请输入验证码">
                                <template #append>
                                    <el-button @click="sendRegisterCode" :disabled="codeSending">
                                        {{ codeButtonText }}
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>

                        <el-form-item class="form-item" prop="password">
                            <el-input :prefix-icon="Lock" v-model="registerForm.password" placeholder="请输入密码"
                                show-password />
                        </el-form-item>

                        <el-form-item class="form-item">
                            <el-button class="submit-btn" :loading="loading" @click="handleRegister">
                                注 册
                            </el-button>
                        </el-form-item>

                        <div class="form-switch">
                            已有账号？<a @click="switchForm('account')">立即登录</a>
                        </div>
                    </el-form>
                </div>

                <!-- 忘记密码表单 -->
                <div v-show="currentForm === 'forgot'" class="form-container">
                    <div class="form-header">
                        <h2 class="form-title">找回账号</h2>
                        <p class="form-subtitle">重置密码,请输入您的邮箱</p>
                    </div>
                    <el-form :model="forgotForm" :rules="rules" ref="forgotFormRef">
                        <el-form-item class="form-item" prop="email">
                            <el-input prefix-icon="el-icon-message" v-model="forgotForm.email" placeholder="请输入注册邮箱" />
                        </el-form-item>

                        <el-form-item class="form-item" prop="code">
                            <el-input prefix-icon="el-icon-key" v-model="forgotForm.code" placeholder="请输入验证码">
                                <template #append>
                                    <el-button @click="sendVerificationCode" :disabled="codeSending">
                                        {{ codeButtonText }}
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>

                        <el-form-item class="form-item" prop="password">
                            <el-input prefix-icon="el-icon-lock" v-model="forgotForm.password" placeholder="请输入新密码"
                                show-password />
                        </el-form-item>

                        <el-form-item class="form-item">
                            <el-button class="submit-btn" :loading="loading" @click="handleResetPassword">
                                重置密码
                            </el-button>
                        </el-form-item>

                        <div class="form-switch">
                            <a @click="switchForm('account')">返回登录</a>
                        </div>
                    </el-form>
                </div>
            </div>
        </div>

        <!-- 滑块验证 -->
        <el-dialog title="请拖动滑块完成拼图" width="360px" v-model="isShowSliderVerify" :close-on-click-modal="false"
            @close="refresh" append-to-body>
            <slider-verify ref="sliderVerifyRef" @success="onSuccess" @fail="onFail" @again="onAgain" />
        </el-dialog>
    </div>
</template>

<script setup>
import { disableScroll, enableScroll } from "@/utils/scroll";
import {
    sendEmailCodeApi,
    registerApi,
    forgotPasswordApi,
    getWechatLoginCodeApi,
    getWechatIsLoginApi,
    getAuthRenderApi,
    getCaptchaSwitchApi,
} from "@/api/auth";
import { setCookie } from "@/utils/cookie";
import SliderVerify from "./components/SliderVerify.vue";
import { ref, onMounted, nextTick, reactive,onUnmounted  } from "vue";
import { useAuthStore } from "@/store";
import { ElMessage } from "element-plus";
import { User, Back,Lock,Key,Message } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const router = useRouter()

// 表单引用（替代this.$refs）
const ruleFormRef = ref(null); // 登录表单
const registerFormRef = ref(null); // 注册表单
const forgotFormRef = ref(null); // 忘记密码表单
const sliderVerifyRef = ref(null); // 滑块验证组件

// 表单验证规则（与原规则一致）
const rules = reactive({
    nickname: [
        { required: true, message: "请输入昵称", trigger: "blur" },
        { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
    ],
    username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" },
    ],
    email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
    ],
    password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" },
    ],
    code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const authStore = useAuthStore()
const currentForm = ref('login')
const loading = ref(false)
// 微信登录相关
const wechatForm = reactive({
    code: "",
    showQrcode: false,
});

// 表单数据（使用reactive定义复杂对象）
const loginForm = reactive({
    username: "",
    password: "",
    source: "PC",
    nonceStr: "",
    value: ""
});

const registerForm = reactive({
    nickname: "",
    email: "",
    password: "",
    code: "",
});

const forgotForm = reactive({
    email: "",
    code: "",
    password: "",
});
const loginTypes = ref({
    github: {
        title: "GitHub账号登录",
        icon: "fab fa-github",
    },
    qq: {
        title: "QQ账号登录",
        icon: "fab fa-qq",
    },
    wechat: {
        title: "微信扫码登录",
        icon: "fab fa-weixin",
    },
    gitee: {
        title: "码云账号登录",
        icon: "fab fa-git-alt",
    },
    weibo: {
        title: "微博账号登录",
        icon: "fab fa-weibo",
    },
})

const codeSending = ref(false)
const codeButtonText = ref("发送验证码")
const codeTimer = ref(null)
const pollingTimer = ref(null)
const isShowSliderVerify = ref(false)
const sliderVerify = ref(null)
const rememberMe = ref(false)

onMounted(async () => {
    Object.keys(loginTypes.value).forEach((key) => {
        if (!authStore.webSiteInfo?.loginTypeList?.includes(key)) {
            delete loginTypes.value[key];
        }
    });
    getWechatLoginCode();
    await nextTick(() => {
        disableScroll();
    });
})

onUnmounted(() => {
    // 启用滚动
    enableScroll();
    // 清除定时器
    clearTimer();
});

//滑块验证成功
const onSuccess = async (captcha) => {
    loginForm.nonceStr = captcha.nonceStr
    loginForm.value = captcha.value
    await login()
}
const login = async () => {
    loading.value = true;
    try {
        console.log("??",loginForm)
        await authStore.loginAction(loginForm);
        
        // 滑块验证成功事件（如果需要）
        sliderVerifyRef.value?.verifySuccessEvent();
        ElMessage.success("登录成功");
        handleClose(); // 登录成功关闭
    } catch (error) {
        ElMessage.error(error.message || "登录失败，请重试");
        refresh(); // 刷新滑块
    } finally {
        loading.value = false;
    }
};

//滑块验证失败
const onFail = () => {
    ElMessage({
        type: 'error',
        message: '验证失败，请重试'
    })
}

//滑块验证重新开始
const onAgain = () => {
    ElMessage({
        type: 'error',
        message: '验证失败，请重试'
    })
}

//刷新
const refresh = () => {
    sliderVerifyRef.value?.refresh()
}

//切换表单
const switchForm = (form) => {
    currentForm.value = form;
    loading.value = false;
    clearTimer(); // 清除定时器
    if (form === "login") {
        getWechatLoginCode(); // 切换到登录表单时重新获取微信验证码
    }
};


/**
 * 账号密码登录表单验证与提交
 */
const handleLogin = async () => {
    // 表单验证（Vue 3中通过ref获取表单实例）
    const ruleFrom = ruleFormRef.value;
    if (!ruleFrom) return;

    // 转换为Promise形式的验证（Element Plus的validate支持Promise）
    try {
        await ruleFrom.validate(); // 验证通过
        // 获取验证码开关配置
        const res = await getCaptchaSwitchApi();
        if (!res.data || res.data.configValue === "Y") {
            // 需要滑块验证
            isShowSliderVerify.value = true;
            console.log("tset",isShowSliderVerify.value)
        } else {
            // 不需要验证，直接登录
            await login();
        }
    } catch (error) {
        // 验证失败
        console.log("表单验证失败:", error);
        return false;
    }
};

/**
 * 注册表单提交
 */
const handleRegister = async () => {
    const registerForm = registerFormRef.value;
    if (!registerForm) return;

    try {
        await registerForm.validate(); // 验证表单
        loading.value = true;
        await registerApi(registerForm.value); // 调用注册API
        ElMessage.success("注册成功");
        switchForm("login"); // 切换到登录
    } catch (error) {
        ElMessage.error(error.message || "注册失败，请重试");
    } finally {
        loading.value = false;
    }
};

/**
 * 重置密码
 */
const handleResetPassword = async () => {
    const forgotForm = forgotFormRef.value;
    if (!forgotForm) return;

    try {
        await forgotForm.validate(); // 验证表单
        loading.value = true;
        await forgotPasswordApi(forgotForm.value); // 调用重置密码API
        ElMessage.success("密码重置成功");
        switchForm("login"); // 切换到登录
    } catch (error) {
        ElMessage.error(error.message || "重置失败，请重试");
    } finally {
        loading.value = false;
    }
};

/**
 * 发送忘记密码的验证码
 */
const sendVerificationCode = async () => {
    if (codeSending.value) return;
    if (!forgotForm.email) {
        ElMessage.error("请先输入邮箱");
        return;
    }
    codeSending.value = true;
    await sendEmailCode(forgotForm.email); // 复用发送验证码逻辑
};

/**
 * 发送注册验证码
 */
const sendRegisterCode = async () => {
    if (codeSending.value) return;
    if (!registerForm.email) {
        ElMessage.error("请先输入邮箱");
        return;
    }
    codeSending.value = true;
    await sendEmailCode(registerForm.email); // 复用发送验证码逻辑
};

/**
 * 发送邮箱验证码（通用）
 */
const sendEmailCode = async (email) => {
    try {
        await sendEmailCodeApi(email); // 调用发送验证码API
        ElMessage.success("发送成功，请前往邮箱查看验证码");

        // 倒计时逻辑
        let countdown = 60;
        codeButtonText.value = `${countdown}秒后重试`;

        codeTimer.value = setInterval(() => {
            countdown--;
            if (countdown <= 0) {
                clearInterval(codeTimer.value);
                codeSending.value = false;
                codeButtonText.value = "发送验证码";
            } else {
                codeButtonText.value = `${countdown}秒后重试`;
            }
        }, 1000);
    } catch (error) {
        ElMessage.error(error.message || "发送失败");
        codeSending.value = false;
    }
};

/**
 * 第三方登录
 */
const handleThirdPartyLogin = async (type) => {
    if (type === "wechat") {
        wechatForm.showQrcode = true;
        getWechatLoginCode();
        return;
    }
    // 获取第三方登录地址
    const res = await getAuthRenderApi(type);
    // 存储跳转地址
    if (!window.location.href.includes("login")) {
        setCookie("redirectUrl", window.location.href);
    }
    window.open(res.data, "_self"); // 打开登录页
};

/**
 * 获取微信登录验证码
 */
const getWechatLoginCode = async () => {
    try {
        const res = await getWechatLoginCodeApi();
        wechatForm.code = res.data;
        pollingWechatIsLogin(); // 开始轮询登录状态

        // 验证码倒计时（60秒后失效）
        let countdown = 60;
        codeTimer.value = setInterval(() => {
            countdown--;
            if (countdown <= 0) {
                clearInterval(codeTimer.value);
                clearInterval(pollingTimer.value);
                wechatForm.code = "验证码已失效";
            }
        }, 1000);
    } catch (error) {
        ElMessage.error("获取验证码失败，请重试");
    }
};

/**
 * 轮询微信登录状态
 */
const pollingWechatIsLogin = () => {
    pollingTimer.value = setInterval(async () => {
        try {
            const res = await getWechatIsLoginApi(wechatForm.code);
            if (res.code === 200) {
                // 登录成功，更新Pinia状态
                authStore.setToken(res.data.token);
                authStore.setUserInfo(res.data);
                clearInterval(pollingTimer.value);
                ElMessage.success("登录成功");
                handleClose(); // 关闭登录页
            }
        } catch (error) {
            console.log("微信登录轮询失败:", error);
        }
    }, 1000);
};

/**
 * 关闭登录页（返回上一页）
 */
const handleClose = () => {
    router.go(-1);
};

const handleSwitchForm = ()=> {
      if (currentForm.value === "login") {
        switchForm("account");
      } else if (currentForm.value === "account") {
        switchForm("login");
      } else {
        switchForm("login");
      }
    }

/**
 * 回到首页
 */
const backToHome = () => {
    router.push("/");
};

/**
 * 清除所有定时器
 */
const clearTimer = () => {
    if (codeTimer.value) {
        clearInterval(codeTimer.value);
        codeTimer.value = null;
    }
    if (pollingTimer.value) {
        clearInterval(pollingTimer.value);
        pollingTimer.value = null;
    }
    codeSending.value = false;
    codeButtonText.value = "发送验证码";
};

</script>


<style scoped lang="scss">
.login-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: url("@/assets/login-bg.svg") no-repeat;
    background-size: cover;
    min-height: 100vh;
    z-index: 2000;
}

.login-body {
    width: 420px;
    padding: 32px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
        0 2px 4px -1px rgba(0, 0, 0, 0.06);
    backdrop-filter: blur(8px);
    background: rgba(255, 255, 255, 0.95);
    position: relative;
}

.form-container {
    animation: fadeIn 0.3s ease;
}

.form-item {
    margin-bottom: 20px;

    :deep(.el-input__inner) {
        height: 44px ;
        font-size: 14px ;
        border: none !important;

        &::placeholder {
            color: #9ca3af ;
        }
    }

    :deep(.el-input__prefix) {
        left: 12px ;
        color: #6b7280 ; 
    }
}

.submit-btn {
    width: 100%;
    height: 42px;
    border: none;
    border-radius: 8px;
    background: #6366f1;
    color: #fff;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
        background: #4f46e5;
        transform: translateY(-1px);
    }

    &:active {
        transform: translateY(0);
    }
}

.divider {
    margin: 24px 0;
    color: #9ca3af;

    :deep(.el-divider__text) {
        background-color: #fff;
        padding: 0 12px;
        font-size: 14px;
    }
}

.third-party-login {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-bottom: 24px;
}

.login-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    cursor: pointer;
    transition: all 0.2s;
    background: #f3f4f6;

    &:hover {
        transform: translateY(-2px);
    }

    &.github {
        color: #24292e;
    }

    &.qq {
        color: #12b7f5;
    }

    &.wechat {
        color: #07c160;
    }

    &.gitee {
        color: #c71d23;
    }

    &.weibo {
        color: #e6162d;
    }
}

.form-switch {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 24px;
    color: #6b7280;
    font-size: 14px;

    a {
        color: $primary;
        text-decoration: none;
        font-weight: 500;
        cursor: pointer;

        &:hover {
            color: darken($primary, 10%);
        }
    }
}

.divider-line {
    color: #e5e7eb;
    margin: 0 12px;
}

.qrcode-content {
    padding: 24px;
    text-align: center;
    animation: fadeIn 0.3s ease;
}

.qrcode-box {
    width: 200px;
    height: 200px;
    margin: 0 auto 16px;
    padding: 8px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;

    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
}

.qrcode-tip {
    margin: 8px 0;
    color: #6b7280;
    font-size: 14px;
}

.code-text {
    color: #6366f1;
    font-weight: 500;

    i {
        cursor: pointer;
        margin-left: $spacing-sm;
    }
}

.form-header {
    text-align: center;
    margin-bottom: 32px;
}

.form-title {
    font-size: 24px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 0 0 8px;
}

.form-subtitle {
    font-size: 14px;
    color: #666;
    margin: 0;
}

.form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.forgot-link {
    color: $primary;
    font-size: 14px;
    cursor: pointer;

    &:hover {
        color: darken($primary, 10%);
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

.switch-form-btn {
    position: absolute;
    top: 16px;
    right: 16px;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    background: #f3f4f6;
    border: none;
    color: #6b7280;

    &:hover {
        background: #e5e7eb;
        transform: rotate(180deg);
    }

    i {
        font-size: 20px;
    }
}

.back-btn {
    position: absolute;
    top: 16px;
    right: 60px;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    background: #f3f4f6;
    border: none;
    color: #6b7280;
    z-index: 1;

    &:hover {
        background: #e5e7eb;
        transform: translateX(-4px);
        color: #6366f1;
    }

    i {
        font-size: 20px;
    }
}
</style>